package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.config.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    //因为SubjectExcelListener不能交给spring托管，所以不能使用@Atuowair注入service从而操作数据库；
    //手动注入service
    public EduSubjectService subjectService;
    //创建无参构造方法
    public SubjectExcelListener() {
    }
    //创建有参构造方法
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        //super.invokeHeadMap(headMap, context);
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new GuliException(20001, "文件数据为空");
        }

        EduSubject existOneSubject = this.ExistOneSubject(subjectService, subjectData.getOneSubjectName());

        if (existOneSubject == null) {

            existOneSubject = new EduSubject();

            existOneSubject.setParentId("0");

            existOneSubject.setTitle(subjectData.getOneSubjectName());

            subjectService.save(existOneSubject);

        }

        String pid = existOneSubject.getId();

        EduSubject existTwoSubject = this.ExistTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);

        if (existTwoSubject == null) {

            existTwoSubject = new EduSubject();

            existTwoSubject.setParentId(pid);

            existTwoSubject.setTitle(subjectData.getTwoSubjectName());

            subjectService.save(existTwoSubject);

        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //一级不能重复
    private EduSubject ExistOneSubject(EduSubjectService subjectService, String name) {

        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();

        wrapper.eq("title", name);

        wrapper.eq("parent_id", "0");

        EduSubject oneSubject = subjectService.getOne(wrapper);

        return oneSubject;
    }

    //二级不能重复
    private EduSubject ExistTwoSubject(EduSubjectService subjectService, String name, String pid) {

        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();

        wrapper.eq("title", name);

        wrapper.eq("parent_id", pid);

        EduSubject twoSubject = subjectService.getOne(wrapper);

        return twoSubject;
    }
}
